class HowBusy
  attr_accessor :project
  attr_accessor :period_type, :period_past, :period_future, :period_from, :period_to, :date_from, :date_to, :date_num
  attr_accessor :projects, :activities, :users, :allowed_projects
  attr_accessor :regular_work_hours

  attr_accessor :issues_by_user, :entries_by_user
  attr_accessor :status
  attr_accessor :messages

  StatusType = {
    :ok => 0,
    :warning => 1,
    :error => 2
  }

  def initialize(project_id, options = { })
    self.project = Project.find(project_id)

    self.status = StatusType[:ok]
    self.messages = []

    self.period_type = options[:period_type].nil? ? 1 : options[:period_type].to_i
    self.period_past = options[:period_past].nil? ? 5 : options[:period_past].to_i
    self.period_future = options[:period_future].nil? ? 7 : options[:period_future].to_i
    self.period_from = options[:period_from].nil? ? Date.today - 5 : options[:period_from].to_date
    self.period_to = options[:period_to].nil? ? Date.today + 7 : options[:period_to].to_date

    if self.period_type == 1 then
      self.date_from = Date.today - self.period_past
      self.date_to = Date.today + self.period_future
    else
      if self.period_from > Date.today then
        self.status = StatusType[:error]
        self.messages << "From日付を本日より後に設定することはできません"
      end
      if self.period_from > self.period_to then
        self.status = StatusType[:error]
        self.messages << "To日付をFrom日付より前に設定することはできません"
      end
      self.date_from = self.period_from
      self.date_to = self.period_to
    end
    self.date_num = self.date_to - self.date_from + 1

    # Get Settings
    self.regular_work_hours = Setting.plugin_redmine_how_busy['regular_work_hours'].to_f

    self.issues_by_user = Hash.new
    self.entries_by_user = Hash.new
    self.project.users.each do |user|
      self.issues_by_user[user.id] = Issue.find(:all,
        :conditions => ["assigned_to_id=? AND #{IssueStatus.table_name}.is_closed=? AND #{Project.table_name}.status=#{Project::STATUS_ACTIVE}", user.id, false],
        :include => [ :status, :project, :tracker, :priority ],
        :order => "#{Enumeration.table_name}.position DESC, #{Issue.table_name}.updated_on DESC")
      self.entries_by_user[user.id] = TimeEntry.find(:all,
        :conditions => ["#{TimeEntry.table_name}.user_id = ? AND #{TimeEntry.table_name}.spent_on BETWEEN ? AND ?", user.id, self.date_from, self.date_to],
        :order => "#{TimeEntry.table_name}.spent_on ASC, #{TimeEntry.table_name}.updated_on ASC")
    end
  end

end
